package com.lixiaohan.controller;

import com.lixiaohan.pojo.Result;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Random;

//import org.springframework.mail.SimpleMailMessage;
//import org.springframework.mail.javamail.JavaMailSenderImpl;

@RestController
@RequestMapping("/email")
public class EmailController {


    @RequestMapping("/put")
    public void TestSuccess(@RequestParam("tomail") String tomail, HttpSession session){
        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:email-config.xml");
        JavaMailSenderImpl javaMailSender = context.getBean("javaMailSender", JavaMailSenderImpl.class);
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom("810848107@qq.com");//发件人
        message.setTo(tomail);//收件人
        message.setSubject("旅蜀道邮箱验证");//主题
        //生成键值对
        int verifyNumberInt = getRandomNumber();
        String verifyNumber=""+verifyNumberInt;
        //向session设置值
        session.setAttribute("verify",verifyNumber);
        //发送正文
        message.setText("您的验证码为："+verifyNumber+",请不要告诉他人");//正文
        javaMailSender.send(message);
        System.out.println("发送完毕");

    }


    public int getRandomNumber(){
        Random random = new Random();
        return random.nextInt(900000)+100000;
    }

    @RequestMapping(value = "/verify",method = RequestMethod.POST)
    public Result veryfy(String inNumber,HttpSession session){
        String verifyNumber = (String) session.getAttribute("verify");
        System.out.println(inNumber);
        System.out.println(verifyNumber);
        if (inNumber.equals(verifyNumber)){
            session.removeAttribute("verify");
            return Result.ok().message("验证成功！");
        }else {
            return Result.error().message("验证码错误！");
        }
    }





}
